<?php
/* SVN FILE: $Id: add.php 221 2009-09-16 19:05:39Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* ibMarket ACP home page
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 221 $
* @lastrevision $Date: 2009-09-16 19:05:39 +0000 (Wed, 16 Sep 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-09-16 19:05:39 +0000 (Wed, 16 Sep 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/modules_admin/items/add.php $
*/


if ( ! defined( 'IN_ACP' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'admin.php'.";
	exit();
}

class admin_ibmarket_items_add extends ipsCommand
{
	/**
	 * Skin object
	 *
	 * @access	private
	 * @var		object			Skin templates
	 */
	private $html;
	
	/**
	 * Main class entry point
	 *
	 * @access	public
	 * @param	object		ipsRegistry reference
	 * @return	void		[Outputs to screen]
	 */
	public function doExecute( ipsRegistry $registry )
	{
		$this->registry->getClass('class_permissions')->checkPermissionAutoMsg( 'item_add' );
		
		$this->html = $this->registry->output->loadTemplate('cp_skin_items');
		
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'admin_market', 'admin_items', 'admin_item_language' ) );
		
		$execute = array(
							'list' => 'listItems',
							'add' => 'addForm',
							'insert' => 'insertItem',
						);
		
		if(!isset($execute[$this->request['do']]))
		{
			$this->request['do'] = 'list';
		}
		
		$function = $execute[$this->request['do']];
		$this->$function();
	}
	
	public function listItems()
	{
		$itemsDirectory = array("");
		foreach(new DirectoryIterator(IPSLib::getAppDir('ibmarket')."/items") as $directory)
		{
			if($directory->isDir() && !$directory->isDot())
			{
				if(file_exists(IPSLib::getAppDir('ibmarket')."/items/".$directory->getFilename()."/info.php"))
				{
					$itemsDirectory[] = $directory->getFilename();
				}
			}
		}
		
		$itemTemplate = new ReflectionClass('templateItem');
		$directoryInfo = array();
		$itemsList = array();
		foreach($itemsDirectory as $directory)
		{
			$title = "";
			$description = "";
			require(IPSLib::getAppDir('ibmarket')."/items/".$directory."/info.php");
			if(!isset($title))
			{
				continue;
			}
			
			$directoryInfo[$directory]['title'] = isset($this->lang->words[$title]) ? $this->lang->words[$title] : $title;
			$directoryInfo[$directory]['description'] = isset($this->lang->words[$description]) ? $this->lang->words[$description] : $description;
			
			$itemsList[$directory] = array();
			$itemsList[$directory][] = array(-1, str_repeat("-",50));
			foreach(new DirectoryIterator(IPSLib::getAppDir('ibmarket')."/items/".$directory) as $file)
			{
				if(strstr($file->getFilename(),"item_") != $file->getFilename() || substr($file->getFilename(),-4) != '.php')
				{
					continue;
				}
				
				require_once(IPSLib::getAppDir('ibmarket')."/items/".$directory."/".$file->getFilename());
				
				$class = new ReflectionClass(marketRegistry::getClassName($file->getFilename()));
				if(!$class->isSubclassOf($itemTemplate))
				{
					continue;
				}
				
				$item = $class->newInstanceArgs(array(&$this->registry,array()));
				$itemName = $item->getDefaultName();
				$itemsList[$directory][] = array($file->getFilename(),$itemName);
			}
		}
		
		$this->registry->output->html = $this->html->listAllPHPItems( $directoryInfo, $itemsList );
		
		$this->registry->getClass('output')->html_main .= $this->registry->getClass('output')->global_template->global_frame_wrapper();
		$this->registry->getClass('output')->sendOutput();
	}
	
	public function addForm()
	{
		ipsRegistry::getClass('adminFunctions')->checkSecurityKey();
		
		$itemInfo = array();
		
		$itemsDirectory = array("");
		foreach(new DirectoryIterator(IPSLib::getAppDir('ibmarket')."/items") as $directory)
		{
			if($directory->isDir() && !$directory->isDot())
			{
				if(file_exists(IPSLib::getAppDir('ibmarket')."/items/".$directory->getFilename()."/info.php"))
				{
					require(IPSLib::getAppDir('ibmarket')."/items/".$directory->getFilename()."/info.php");
					if(!isset($title))
					{
						continue;
					}
					$itemsDirectory[] = $directory->getFilename();
				}
			}
		}
		
		$itemTemplate = new ReflectionClass('templateItem');
		$item = null;
		$file = "";
		foreach($itemsDirectory as $directory)
		{
			if(!isset($this->request['directory'][$directory]) || $this->request['directory'][$directory] == -1)
			{
				continue;
			}
			if(!file_exists(IPSLib::getAppDir('ibmarket')."/items/".$directory."/".$this->request['directory'][$directory]))
			{
				continue;
			}
			if(strstr($this->request['directory'][$directory],"item_") != $this->request['directory'][$directory] || substr($this->request['directory'][$directory],-4) != '.php')
			{
				continue;
			}
			require_once(IPSLib::getAppDir('ibmarket')."/items/".$directory."/".$this->request['directory'][$directory]);
			
			$class = new ReflectionClass(marketRegistry::getClassName($this->request['directory'][$directory]));
			if(!$class->isSubclassOf($itemTemplate))
			{
				continue;
			}
			
			$item = $class->newInstanceArgs(array(&$this->registry,&$itemInfo));
			$file = $directory."/".$this->request['directory'][$directory];
			break;
		}
		if(is_null($item))
		{
			$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=items&amp;section=add" );
		}
		if(!$item->allowMultipleInstances() && !is_null(marketRegistry::getItemsByFiles($input['filename'])) && count(marketRegistry::getItemsByFiles($input['filename'])) > 1)
		{
			$this->registry->output->showError( $this->lang->words['cannot_put_child_as_parent'] );
		}
		
		$null1 = array();
		$null2 = array();
		
		$itemInfo['item_id']			= 0;
		$itemInfo['item_name']			= $item->getDefaultName();
		$itemInfo['item_description']	= $item->getDefaultDescription();
		$itemInfo['filename']			= $file;
		$itemInfo['category']			= null;
		$itemInfo['icon']				= null;
		$itemInfo['hide_item']			= $item->publicOnCreateItem($null1) ? 0 : 1;
		$itemInfo['base_price']			= 0;
		$itemInfo['base_resell']		= 0;
		$itemInfo['tax']				= 0;
		$itemInfo['stock']				= -1;
		$itemInfo['allow_resell']		= $item->publicOnResoldItem($null2) ? 1 : 0;
		$itemInfo['resell_putback']		= 1;
		$itemInfo['expire_time']		= 0;
		$itemInfo['expire_unit']		= 60;
		$itemInfo['inventory_limit']	= 0;
		$itemInfo['limit_buy']			= array();
		$itemInfo['limit_use']			= array();
		$itemInfo['restock_howmuch']	= 0;
		$itemInfo['restock']			= 0;
		$itemInfo['restock_when']		= "";
		$itemInfo['restock_minute']		= 0;
		$itemInfo['restock_hour']		= 0;
		$itemInfo['restock_day']		= 0;
		
		$passed = true;
		$dependencies = $item->getDependcies();
		if(is_array($dependencies['item']) && count($dependencies['item']))
		{
			foreach($dependencies['item'] as $itemFile)
			{
				if(is_null(marketRegistry::getItemsByFiles($itemFile)))
				{
					$passed = false;
				}
			}
		}
		if(is_array($dependencies['plugin']) && count($dependencies['plugin']))
		{
			foreach($dependencies['plugin'] as $pluginFile)
			{
				if(is_null(marketRegistry::getPluginByFiles($pluginFile)))
				{
					$passed = false;
				}
			}
		}
		if(isset($dependencies['server']['ibmarket']))
		{
			if($this->caches['app_cache']['ibmarket']['app_long_version'] < $dependencies['server']['ibmarket'])
			{
				$passed = false;
			}
		}
		if(isset($dependencies['server']['ipboard']))
		{
			if($this->caches['app_cache']['core']['app_long_version'] < $dependencies['server']['ipboard'])
			{
				$passed = false;
			}
		}
		if(isset($dependencies['server']['php']))
		{
			if(version_compare(PHP_VERSION, $dependencies['server']['php']) < 0)
			{
				$passed = false;
			}
		}
		if(!$passed)
		{
			$this->registry->output->showError( $this->lang->words['not_pass_requirements'] );
		}
		
		$this->registry->output->html = $this->html->itemForm( $item, $itemInfo, 'add', 'insert', $this->lang->words['add_item_title'], $this->lang->words['add_item_button'] );
		
		$this->registry->getClass('output')->html_main .= $this->registry->getClass('output')->global_template->global_frame_wrapper();
		$this->registry->getClass('output')->sendOutput();
	}
	
	public function insertItem()
	{
		ipsRegistry::getClass('adminFunctions')->checkSecurityKey();
		
		if(!is_array($this->request['item']))
		{
			$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=items&amp;section=add" );
		}
		
		$input =& $this->request['item'];
		
		if(!$input['filename'] || !file_exists(IPSLib::getAppDir('ibmarket')."/items/".$input['filename']) || substr($input['filename'],-4) != '.php')
		{
			$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=items&amp;section=add" );
		}
		
		$itemTemplate = new ReflectionClass('templateItem');
		require_once(IPSLib::getAppDir('ibmarket')."/items/".$input['filename']);
		$class = new ReflectionClass(marketRegistry::getClassName($input['filename']));
		if(strstr($class->getName(),"item_") != $class->getName())
		{
			$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=items&amp;section=add" );
		}
		if(!$class->isSubclassOf($itemTemplate))
		{
			$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=items&amp;section=add" );
		}
		$item = $class->newInstanceArgs(array(&$this->registry,array()));
		if(!$item->allowMultipleInstances() && !is_null(marketRegistry::getItemsByFiles($input['filename'])) && count(marketRegistry::getItemsByFiles($input['filename'])) > 1)
		{
			$this->registry->output->showError( $this->lang->words['cannot_have_multiple_items'] );
		}
		
		$passed = true;
		$dependencies = $item->getDependcies();
		if(is_array($dependencies['item']) && count($dependencies['item']))
		{
			foreach($dependencies['item'] as $itemFile)
			{
				if(is_null(marketRegistry::getItemsByFiles($itemFile)))
				{
					$passed = false;
				}
			}
		}
		if(is_array($dependencies['plugin']) && count($dependencies['plugin']))
		{
			foreach($dependencies['plugin'] as $pluginFile)
			{
				if(is_null(marketRegistry::getPluginByFiles($pluginFile)))
				{
					$passed = false;
				}
			}
		}
		if(isset($dependencies['server']['ibmarket']))
		{
			if($this->caches['app_cache']['ibmarket']['app_long_version'] < $dependencies['server']['ibmarket'])
			{
				$passed = false;
			}
		}
		if(isset($dependencies['server']['ipboard']))
		{
			if($this->caches['app_cache']['core']['app_long_version'] < $dependencies['server']['ipboard'])
			{
				$passed = false;
			}
		}
		if(isset($dependencies['server']['php']))
		{
			if(version_compare(PHP_VERSION, $dependencies['server']['php']) < 0)
			{
				$passed = false;
			}
		}
		if(!$passed)
		{
			$this->registry->output->showError( $this->lang->words['not_pass_requirements'] );
		}
		
		$input['description'] = IPSText::getTextClass('bbcode')->preDbParse(IPSText::getTextClass('editor')->processRawPost('item_description'));
		
		$input['restock'] = intval($input['restock']);
		if($input['restock'] == 1 || $input['restock'] == 2)
		{
			$input['restock_when'] = numbers::max(0,numbers::parseInt($input['restock_when']));
		}
		elseif($input['restock'] == 3)
		{
			list($date, $time) = explode(" ",$input['restock_when']);
			list($month,$day,$year) = explode("/",$date);
			list($hour,$minute) = explode(":",$time);
			$input['restock_when'] = gmmktime( intval($hour), intval($minute), 0, intval($month), intval($day), intval($year) );
		}
		elseif($input['restock'] == 4)
		{
			$input['restock_when'] = 0;
		}
		else
		{
			$input['restock'] = 0;
			$input['restock_when'] = 0;
		}
		
		if(!is_array($this->caches['market_category'][$input['category']]))
		{
			$this->registry->output->showError( $this->lang->words['invalid_category'] );
		}
		
		$itemInfo = array(
							'filename' => $input['filename'],
							'item_name' => $input['item_name'],
							'item_description' => $input['description'],
							'category' => $input['category'],
							'icon' => $input['icon'],
							'hide_item' => intval($input['hide_item']) & 1,
							'base_price' => numbers::max(numbers::parseInt($input['base_price']),0),
							'base_resell' => numbers::max(numbers::parseInt($input['base_resell']),0),
							'allow_resell' => intval($input['allow_resell']) & 1,
							'resell_putback' => intval($input['resell_putback']) & 1,
							'tax' => numbers::parseFloat($input['tax']),
							'stock' => $input['stock'] == 'infinite' ? -1 : numbers::max(numbers::parseInt($input['stock']),-1),
							'restock' => $input['restock'],
							'restock_when' => $input['restock_when'],
							'restock_minute' => max(min(intval($input['restock_minute']), 60), 0),
							'restock_hour' => max(min(intval($input['restock_hour']), 24), 0),
							'restock_day' => max(min(intval($input['restock_day']), 7), 0),
							'restock_howmuch' => numbers::parseInt($input['restock_howmuch']),
							'inventory_limit' => numbers::parseInt($input['inventory_limit']),
							'limit_buy' => serialize(is_array($input['limit_buy']) ? $input['limit_buy'] : array()),
							'limit_use' => serialize(is_array($input['limit_use']) ? $input['limit_use'] : array()),
							'expire_time' => intval($time['expire_time']),
							'expire_unit' => intval($time['expire_unit']),
						);
		
		$itemInfo['restock_time'] = marketRegistry::nextRestockTime($itemInfo);
		
		$item = $class->newInstanceArgs(array(&$this->registry,&$itemInfo));
		$item->adminSave($itemInfo, $input);
		
		if(!isset($itemInfo['item_config']))
		{
			$itemInfo['item_config'] = '';
		}
		
		if(!isset($itemInfo['settings']))
		{
			$itemInfo['settings'] = '';
		}
		
		$this->DB->insert('market_items',$itemInfo);
		$item_id = $this->DB->getInsertId();
		
		$this->cache->rebuildCache('market_items','ibmarket');
		
		$this->lang->words['item_add_log'] = str_replace("<#NAME#>",$input['item_name'],$this->lang->words['item_add_log']);
		$this->lang->words['item_add_log'] = str_replace("<#ID#>",$item_id,$this->lang->words['item_add_log']);
		ipsRegistry::getClass('adminFunctions')->saveAdminLog( $this->lang->words['item_add_log'] );
		
		$this->registry->output->global_message .= $this->lang->words['item_added'];
		if($item->adminViewFileEdits())
		{
			list($directory, $filename) = explode("/",$input['filename']);
			$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=items&amp;section=fileedits&amp;do=edits&amp;directory[".$directory."]=".$filename );
		}
		else
		{
			$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=items&amp;section=view&amp;category=".$input['category'] );
		}
	}
}